<template>
  <div class="add-member-to-activity">
    <!-- 活动信息 -->
    <el-card class="activity-info">
      <template #header>
        <h3>活动信息</h3>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="活动编号">
          {{ activityInfo.id }}
        </el-descriptions-item>
        <el-descriptions-item label="活动名称">
          {{ activityInfo.activityName }}
        </el-descriptions-item>
        <el-descriptions-item label="所属社团">
          {{ activityInfo.clubName }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 用户查询 -->
    <el-card class="user-search">
      <template #header>
        <h3>查询用户</h3>
      </template>
      <el-input
        v-model="userIdInput"
        placeholder="请输入用户ID"
        class="input-with-select"
      >
        <template #append>
          <el-button @click="searchUser">查询</el-button>
        </template>
      </el-input>
    </el-card>

    <!-- 用户信息显示 -->
    <el-card v-if="userInfo" class="user-info">
      <template #header>
        <h3>用户信息</h3>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">
          {{ userInfo.userId }}
        </el-descriptions-item>
        <el-descriptions-item label="用户名">
          {{ userInfo.userName }}
        </el-descriptions-item>
        <el-descriptions-item label="年级">
          {{ userInfo.grade }}
        </el-descriptions-item>
        <el-descriptions-item label="专业">
          {{ userInfo.major }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 用户不存在提示 -->
    <el-alert
      v-if="showNoUserAlert"
      title="目标用户不存在"
      type="warning"
      :closable="false"
    />

    <!-- 确认添加按钮 -->
    <el-button type="primary" class="confirm-button" @click="confirmAddMember">
      确认添加
    </el-button>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { type Action, ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import {
  ActivityControllerService,
  type ActivityMembershipUpdateRequest,
  AdminActivityControllerService,
  AdminUserControllerService,
} from "../../../../generated";

interface SearchUserInfo {
  userId: number;
  userName: string;
  grade: string;
  major: string;
  userClass: string;
}

interface ActivityInfo {
  id: number;
  activityName: string;
  clubName: string;
}

const route = useRoute();
const activityIdStr = Number(route.query.activityId);
const activityId = Number(activityIdStr);
const activityInfo = ref<ActivityInfo>({
  id: 0,
  activityName: "",
  clubName: "",
});

const loadData = async () => {
  try {
    const activityRes =
      await ActivityControllerService.getActivityVoById(activityId);
    if (activityRes.code === 0) {
      activityInfo.value = {
        id: activityRes.data?.id as number,
        activityName: activityRes.data?.activityName as string,
        clubName: activityRes.data?.clubVO?.clubName as string,
      };
    } else {
      ElMessage.error("加载数据失败：" + (activityRes.message || "未知错误"));
    }
  } catch (error) {
    console.error("加载数据时发生错误:", error);
    ElMessage.error("加载数据时发生错误，请稍后重试");
  }
};

onMounted(() => {
  loadData();
});

// 用户ID输入
const userIdInput = ref("");

// 用户信息
const userInfo = ref<SearchUserInfo>({});

// 控制是否显示用户不存在的提示
const showNoUserAlert = ref(false);

// 查询用户信息
const searchUser = async () => {
  // 重置状态
  userInfo.value = {};
  showNoUserAlert.value = false;

  if (!userIdInput.value) {
    ElMessage.warning("请输入用户ID");
    return;
  }

  try {
    const userRes = await AdminUserControllerService.getUserVoById(
      Number(userIdInput.value),
    );
    if (userRes.code === 0) {
      userInfo.value = {
        userId: userRes.data?.id as number,
        userName: userRes.data?.userName as string,
        grade: userRes.data?.grade as string,
        major: userRes.data?.major as string,
        userClass: userRes.data?.userClass as string,
      };
    } else {
      ElMessage.error("查询数据时发生错误，请稍后重试");
    }
  } catch (error) {
    console.error("查询数据时发生错误:", error);
    ElMessage.error("查询数据时发生错误，请稍后重试");
  }
};

// 确认添加成员到活动
const confirmAddMember = async () => {
  if (!userInfo.value) {
    ElMessage.warning("请先查询并选择要添加的用户");
    return;
  }

  try {
    const addRes = await AdminActivityControllerService.addMemberToActivity({
      activityId: activityId,
      userId: userInfo.value.userId,
    } as ActivityMembershipUpdateRequest);

    if (addRes.code === 0) {
      const successStr = `用户 ${userInfo.value.userName} 已成功添加到活动 ${activityInfo.value.activityName}`;
      ElMessageBox.alert(successStr, "添加成功", {
        confirmButtonText: "确定",
        callback: (action: Action) => {
          if (action === "confirm") {
            try {
              // 重置状态
              userIdInput.value = "";
              userInfo.value = null;
            } catch (e) {
              ElMessage({
                type: "info",
                message: "无法自动重置页面状态，请手动刷新页面。",
                duration: 0,
                showClose: true,
              });
            }
          }
        },
      });
    } else {
      const errorStr = "错误原因: " + addRes.message;
      ElMessageBox.alert(errorStr, "添加失败", {
        confirmButtonText: "确定",
        callback: (action: Action) => {
          if (action === "confirm") {
            window.location.reload(); // 刷新当前页面
          }
        },
      });
    }
  } catch (error) {
    console.error("添加成员到活动失败:", error);
    ElMessage.error("添加成员失败，请稍后重试");
  }
};
</script>
<style scoped>
.add-member-to-activity {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.activity-info,
.user-search,
.user-info {
  margin-bottom: 20px;
}

.input-with-select {
  margin-bottom: 15px;
}

.confirm-button {
  width: 100%;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
